import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/mine/user_manage/mine_add_user/models/organization_model.dart';
import 'package:yt_devops/pages/mine/user_manage/models/user_manager_model.dart';
import 'package:yt_devops/pages/mine/user_manage/user_manage_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

class UserManagerUserDetailController extends GetxController {
  final TextEditingController roleController = TextEditingController();
  final TextEditingController statusController = TextEditingController();
  final TextEditingController userNameController = TextEditingController();
  final TextEditingController mobileController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController relationSiteController = TextEditingController();
  final TextEditingController organizationController = TextEditingController();
  final _authServices = Get.put(AuthServices());
  bool enableCommit = false;
  bool isEnableEdit = false;
  String avatar = '';
  List<String> conditions = [
    ResKey.installManu.tr,
    ResKey.mineUserManagerUserOwner.tr
  ];
  List<String> statusList = [
    ResKey.mineUserManagerUserValid.tr,
    ResKey.mineUserManagerUserInvalid.tr
  ];
  List<String> roleId = ['3', '4'];

  int selectedRoleIndex = -1;
  int selectedStatusIndex = 0;
  UserManagerModel model = UserManagerModel();

  List chooseSiteList = [];
  List chooseSiteMapList = [];
  List originSiteMapList = [];
  String userAccount = '';

  ///获取到的站点原始数据,点击取消要重新遍历
  UserManageController controller = Get.find();
  int roleTypeId = RoleType.owner.value;
  List<OrganizationModel> organizationList = [];
  List<String> organizationShowList = [];
  int selectedOrganizationIndex = 0;
  var organizationId = '';
  var selectedID = ''; //选中的组织id,用户下次进入选择组织页面的回显
  List orgTypes = [0];
  var orgId = '';
  String selectedRoleId = '';
  List<String> roleShowList = [];
  List<dynamic> rolesList = [];
  int type = 0;
  bool editAuth = false;

  bool isShowRole = false;
  List<String> systemBuiltRoles = [
    '1',//超级管理员
    '3',//安装商
    '5',//运营商
    '7',//访客
    '29'//系統管理员
  ]; //系统内置角色都不能关联站点(除了业主)
  final TextEditingController remarkController = TextEditingController();
  List pushTypeList = [];//推送方法数组
  List pushLevelList = [];//推送级别数组
  // List selectedSitesIds = [];
  List selectedSitesNames = [];
  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      if (Get.arguments['model'] != null) {
        model = Get.arguments['model'];
      }
      if (Get.arguments['type'] != null) {
        type = Get.arguments['type'];
      }
      if (Get.arguments['editAuth'] != null) {
        editAuth = Get.arguments['editAuth'];
      }
      _initData();
      checkCanCommit();
      getUserDetail();
    }
  }

  _initData() {
    avatar = model.avatar ?? '';
    userNameController.text =
        model.nickName != null && model.nickName!.isNotEmpty
            ? model.nickName!
            : '--';
    userAccount = model.userName != null && model.userName!.isNotEmpty
        ? model.userName!
        : '--';
    mobileController.text =
        model.phone != null && model.phone!.isNotEmpty ? model.phone! : '--';
    emailController.text =
        model.email != null && model.email!.isNotEmpty ? model.email! : '--';
    if (relationSiteController.text.isEmpty) {
      relationSiteController.text = '--';
    }
    if (model.roles != null && model.roles![0].roleName != null) {
      roleController.text = model.roles![0].roleName.toString();
      selectedRoleId = model.roles![0].roleId!.toString();
    }
    orgId = model.orgId != null ? model.orgId.toString() : '';
    selectedStatusIndex = (model.status != null && model.status == '0') ? 0 : 1;
    statusController.text = statusList[selectedStatusIndex].toString();
    if (UserEntityManager().userModel.roles != null) {
      roleTypeId = UserEntityManager().userModel.roles![0].roleId!;
    }
    organizationController.text =
        model.orgName != null && model.orgName!.isNotEmpty
            ? model.orgName!
            : '--';
    if (UserEntityManager().userModel.roles != null //20231220最新需求觉得无法更改,次方法无用
        &&
        UserEntityManager().userModel.roles?[0].roleId! == 6) {
      //产品管理员组织和角色都能改,并且选择角色更多
      conditions = [
        ResKey.installManu.tr,
        ResKey.mineUserManagerUserOwner.tr,
        ResKey.productManager.tr,
      ];
      roleId = ['3', '4', '6'];
    }
    if (chooseSiteMapList.isNotEmpty) {
      if (chooseSiteMapList.length == 1) {
        relationSiteController.text = chooseSiteMapList.first['name'];
      } else {
        relationSiteController.text = chooseSiteMapList.first['name'] + '...';
      }
      chooseSiteList.clear();
      for (var element in chooseSiteMapList) {
        chooseSiteList.add(element['id'].toString());
      }
      // selectedSitesIds = chooseSiteList;
    }
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  ///检查是否可以提交
  void checkCanCommit() {
    if (statusController.text.isNotEmpty &&
        userNameController.text.isNotEmpty &&
        roleController.text.isNotEmpty &&
        organizationController.text.isNotEmpty &&
        pushTypeList.isNotEmpty && pushLevelList.isNotEmpty) {
      if(systemBuiltRoles.contains(selectedRoleId)){
        enableCommit = true;
      }else {
        if(!systemBuiltRoles.contains(selectedRoleId) && relationSiteController.text.isNotEmpty){
          Log.d('checkCanCommit===' + enableCommit.toString());
          enableCommit = true;
        }else{
          Log.d('checkCanCommit===' + enableCommit.toString());
          enableCommit = false;
        }
      }
    } else {
      enableCommit = false;
    }
    Log.d('checkCanCommit===' + pushTypeList.toString());
    Log.d('checkCanCommit===' + pushLevelList.toString());
    Log.d('checkCanCommit===' + enableCommit.toString());
    update();
  }


  getUserDetail() async {
    showLoading(toast: ResKey.loading.tr);
    var result = await _authServices
        .getUserManagerDetail({'userId': model.userId}, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    Log.d('alarmPushLevels===' + result['user'].toString());
    if (result != null && result['roleIds'] != null) {
      List list = result['roleIds'];
      if (list.isNotEmpty) {
        selectedRoleId = list.first.toString();
        Log.d('selectedRoleId===' + selectedRoleId.toString());
      }
    }
    pushTypeList= result?['user']?['alarmPushModes']??[];
    pushLevelList = result?['user']?['alarmPushLevels']??[];
    remarkController.text = result?['user']?['remark']??'';
    if (result != null &&
        result['user'] != null &&
        result['user']['sites'] != null) {
      chooseSiteMapList = result['user']['sites'];
      originSiteMapList = result['user']['sites'];
      if (chooseSiteMapList.isNotEmpty) {
        if (chooseSiteMapList.length == 1) {
          relationSiteController.text = chooseSiteMapList.first['name'];
        } else {
          relationSiteController.text = chooseSiteMapList.first['name'] + '...';
        }
        chooseSiteList.clear();
        for (var element in chooseSiteMapList) {
          chooseSiteList.add(element['id'].toString());
        }
        // selectedSitesIds = chooseSiteList;
      }
    }
    Log.d('pushLevelList===' + pushLevelList.toString());
    checkCanCommit();
    update();
  }

  Future<void> save() async {
    var param = {
      'avatar': avatar,
      "userId": model.userId ?? 0,
      "nickName": userNameController.text,
      "userName": userAccount,
      "phone": mobileController.text,
      "orgId": orgId ?? 0,
      "roleIds": [selectedRoleId],
      "status": selectedStatusIndex,
      'email': emailController.text,
      'siteIds': chooseSiteList,
      'webConfig':chooseSiteList,
      'alarmPushModes': pushTypeList,
      'alarmPushLevels': pushLevelList,
      'remark': remarkController.text??''
    };
    Log.d('param==' + param.toString());
    Log.d('param==' + param.toString());
    showLoading(toast: ResKey.loading.tr);
    var result =
        await _authServices.eEditUserManagerDetail(param, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      FuncUtils.requestTipsDislog(
          Get.context, ResKey.mineUserManagerUpdateSuccess.tr, true,
          duration: const Duration(milliseconds: 1000),
          backgroundColor: Colors.transparent);
      controller.onRefresh();
      Future.delayed(const Duration(milliseconds: 1000), () {
        // 延迟执行的代码
        Get.back();
      });
    }
  }

  void cancel() {
    if (emailController.text.isEmpty) {
      emailController.text = '--';
    }
    if (userNameController.text.isEmpty) {
      userNameController.text = '--';
    }
    if (mobileController.text.isEmpty) {
      mobileController.text = '--';
    }
    if (relationSiteController.text.isEmpty) {
      relationSiteController.text = '--';
    }
    isEnableEdit = false;
    _initData();
    Log.d('chooseSiteMapList===' + chooseSiteMapList.toString());
    if (originSiteMapList.isNotEmpty) {
      if (originSiteMapList.length == 1) {
        relationSiteController.text = originSiteMapList.first['name'];
      } else {
        relationSiteController.text = originSiteMapList.first['name'] + '...';
      }
      chooseSiteList.clear();
      for (var element in originSiteMapList) {
        chooseSiteList.add(element['id'].toString());
      }
      // selectedSitesIds = chooseSiteList;
    }
    update();
  }
  ///选择组织
  chooseOrganization() async {

      ///产品管理员和自定义角色type都传0 ,1安装商  3业主/运营商
      if (selectedRoleId.isEmpty) {
        showError(ResKey.pleSelectARole.tr);
        return;
      }
      // if(selectedRoleId == '3' || selectedRoleId == '4'){//如果是安装商或者业主则底部弹出选择 不需要组织树,else跳转其他页面需要组织树
      showLoading(toast: ResKey.loading.tr);
      String type = '0';
      if (selectedRoleId == '3') {
        ///安装商角色
        type = '1';
      } else if (selectedRoleId == '4'|| selectedRoleId == '36') {
        ///业主
        type = '3';
      }
      List result = await _authServices.productOrganizationList({'type': type},
          onError: (error) {
            dismissLoading();
            handleException(error);
            return false;
          });
      dismissLoading();
      if (result.isNotEmpty) {
        organizationShowList.clear();
        organizationList.clear();
        for (int i = 0; i < result.length; i++) {
          var element = result[i];
          organizationList.add(OrganizationModel.fromJson(element));
          organizationShowList.add(element['orgName']);
          if (orgId.toString() == element['orgId'].toString()) {
            selectedOrganizationIndex = i;
          }
        }

        showBottomPop(
          organizationShowList,
          ResKey.selectOrganization.tr,
        );
      }

  }

  ///弹出底部弹窗
  showBottomPop(List<String> list, String title, {bool isOrganization = true}) {
    BrnMultiDataPicker(
      context: Get.context!,
      title: title,
      confirmClick: (indexList) {
        if (isOrganization) {
          selectedOrganizationIndex = indexList[0];
          OrganizationModel model = organizationList[selectedOrganizationIndex];
          organizationController.text = model.orgName ?? '';
          orgId = model.orgId != null ? model.orgId.toString() : '';
          selectedID = orgId;
          relationSiteController.text = '';
          chooseSiteList = [];
          Log.d('orgId===' + orgId.toString());
        } else {
          if (selectedRoleIndex == indexList[0]) {
            ///选择的角色和当前角色一样则不进行任何操作
            return;
          }
          selectedRoleIndex = indexList[0];
          organizationController.text = '';
          orgId = '';
          selectedRoleId = rolesList[selectedRoleIndex]['roleId'].toString();
          roleController.text = roleShowList[selectedRoleIndex];
          relationSiteController.text = '';
          chooseSiteList = [];
        }
        checkCanCommit();
        update();
      },
      delegate: Brn1RowDelegate(list,
          firstSelectedIndex:
              isOrganization ? selectedOrganizationIndex : selectedRoleIndex),
    ).show();
  }

  void edit() {
    isEnableEdit = true;
    if (emailController.text == '--') {
      emailController.text = '';
    }
    if (userNameController.text == '--') {
      userNameController.text = '';
    }
    if (mobileController.text == '--') {
      mobileController.text = '';
    }
    if (relationSiteController.text == '--') {
      relationSiteController.text = '';
    }
    update();
  }

  ///跳转关联站点
  chooseRelateSite() {

    if(type == 0){
      if (selectedRoleId.isEmpty) {
        showError(ResKey.mineUserManagerUserChooseRole.tr);
      } else {

        Get.toNamed(RouterPath.adminChooseRelateSite, arguments: {
          'roleId': selectedRoleId,
          'selectedSitesIds':chooseSiteList,
          'selectedSitesNames':selectedSitesNames
        })?.then((result){
          if(result != null){
            if(result['selectedSitesNames'] != null) {
              selectedSitesNames = result['selectedSitesNames'];
              if (selectedSitesNames.length > 1) {
                relationSiteController.text = selectedSitesNames.first + '...';
              } else {
                relationSiteController.text = selectedSitesNames.first;
              }
            }
            List<dynamic> selectedSitesIds = [];
            if (result['selectedSitesIds'] != null) {

              selectedSitesIds = result['selectedSitesIds'];
            }
            if(result['returnList'] != null && result['returnList'].isNotEmpty && selectedSitesIds.isNotEmpty){
              List siteList = result['returnList'];
              // chooseSiteList.clear();
              for (var element in siteList) {
                if(selectedSitesIds.contains(element['id'].toString())){
                  List<String> siteIds = collectSiteIds(element, element['id'].toString());
                  chooseSiteList.addAll(siteIds);
                }
              }
              chooseSiteList.removeWhere((id) => id.startsWith("#"));
            }
            update();
            checkCanCommit();
          }

        });
      }
    }else {
      Log.d('chooseRelateSite==' + chooseSiteList.toString());
      Get.toNamed(RouterPath.mineUserManagerChooseSite,
          arguments: {'orgId': orgId, 'chooseSite': chooseSiteList});
    }
  }

  chooseSiteListCallBack(List list) {
    Log.d('chooseRelateSite==111' + chooseSiteList.toString());
    chooseSiteMapList = list;
    if (list.isNotEmpty) {
      if (list.length == 1) {
        relationSiteController.text = list.first['name'];
      } else {
        relationSiteController.text = list.first['name'] + '...';
      }
      chooseSiteList.clear();
      for (var element in list) {
        chooseSiteList.add(element['id'].toString());
      }
    }
    checkCanCommit();
    update();
  }

  ///如果是产品管理员或者admin这类角色需要去调用接口拿到所有可以展示的角色
  chooseRole() async {
    Log.d('selectedRoleId==' + selectedRoleId.toString());
    showLoading(toast: ResKey.loading.tr);
    var params = {'builtInRole': type == 0 ? 0 : 1, 'manageOrgType': type};
    var result = await _authServices.getRoleList(params, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();

    if (result != null) {
      List<dynamic> list = result;
      if (list.isNotEmpty) {
        Log.d('list===' + list.toString());
        rolesList.clear();
        roleShowList.clear();
        for (int i = 0; i < list.length; i++) {
          var element = list[i];
          roleShowList.add(element['roleName']);
          rolesList.add(element);
          if (element['roleId'].toString() == selectedRoleId) {
            selectedRoleIndex = i;
          }
        }
        showBottomPop(roleShowList, ResKey.mineUserManagerUserChooseRole.tr, isOrganization: false);
      }
    }
  }

  // 递归遍历方法
  List<String> collectSiteIds(dynamic node, String targetId) {
    // 如果找到目标ID
    if (node['id'] == targetId) {
      // 获取当前节点ID
      List<String> ids = [node['id']];
      // 确保 children 存在且非空
      if (node['children'] != null && node['children'].isNotEmpty) {
        // 递归遍历所有子节点并收集它们的ID
        ids.addAll(node['children']
            .expand<String>((child) => collectSiteIds(child, child['id']))
            .toList());
      }
      return ids;
    }
    // 如果当前节点不是目标ID，则继续递归查找子节点
    if (node['children'] != null && node['children'].isNotEmpty) {
      for (var child in node['children']) {
        List<String> result = collectSiteIds(child, targetId);
        if (result.isNotEmpty) {
          return result;
        }
      }
    }
    // 如果没有匹配的ID，则返回空列表
    return [];
  }
}
